package risoe.syslab.fhnew.hw;

/*
 * Copyright (c) 2012-2014, Technical University of Denmark (DTU)
 * All rights reserved.
 * 
 * The Flexhouse 2.0 platform ("this software") is licensed under the
 * BSD 3-clause license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   - Neither the name of DTU nor the names of its contributors may be used to
 *     endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE TECHNICAL UNIVERSITY OF DENMARK BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.util.ArrayList;
import java.util.HashMap;

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
import risoe.syslab.fhnew.common.SystemConstants.DeviceType;
import risoe.syslab.fhnew.config.ActuatorConfig;
import risoe.syslab.fhnew.config.Enocean3InterfaceConfig;
import risoe.syslab.fhnew.config.HWInterfaceConfig;
import risoe.syslab.fhnew.config.SensorConfig;
import risoe.syslab.fhnew.hw.enocean3.ESP3Frame;
import risoe.syslab.fhnew.hw.enocean3.ESP3Packet;
import risoe.syslab.fhnew.hw.enocean3.EnoceanSwitch;
import risoe.syslab.model.CompositeMeasurement;
import risoe.syslab.model.Quality;
import risoe.syslab.model.Source;
import risoe.syslab.model.Validity;

/**
 * HardwareInterface for communicating with Enocean devices utilizing the ESP3 protocol. 
 * @author M. Svendsen
 */
public class Enocean3Interface extends HardwareInterface implements ConnectionManagerInterface{
	private static final int BYTES_MSG = 21;
	public static final int BAUD_RATE = 57600;

	private String mSerialAddress;

	// Map of all enocean devices
	private HashMap<String, String> mDeviceMap = new HashMap<String, String>();
	private SerialPort mSerialPort;
	private ConnectionManager mConnectionManager;

	public Enocean3Interface(HWInterfaceConfig hic) {
		super(hic);
		mSerialAddress = ((Enocean3InterfaceConfig)hic).getSerialAddress();
	}

	@Override
	protected void startInterfaceImpl(ArrayList<SensorConfig> sensors, ArrayList<ActuatorConfig> actuators) {
		// Map all enocean devices
		for (SensorConfig sensor : sensors){
			if (sensor.getInterfaceName().equals(getName())){
				if (sensor.getType() == DeviceType.Button){
					// This is an enocean switch device
					String sensorId = sensor.getInterfaceAttributes().get("id");

					// Get bitmasks related to this enocean switch
					String[] bitmasks = new String[2];
					bitmasks[0] = sensor.getInterfaceAttributes().get("addr");
					bitmasks[1] = sensor.getInterfaceAttributes().get(sensor.getAliases("addr")[0]);

					for (String b : bitmasks){
						mDeviceMap.put(sensorId+":"+Integer.parseInt(b, 16), sensor.getName());
					}
				}
			}
		}

		getLogger().logEvent(getName(), "Initialization", "Complete");

		// Hand off the connection specifics to the ConnectionManager
		mConnectionManager = new ConnectionManager(this);
		mConnectionManager.startConnection();
	}

	@Override
	public boolean connect(){
		try {
			// Find the correct port and open a connection
			mSerialPort = new SerialPort(mSerialAddress);
			mSerialPort.openPort();

			// Initialize the serial port
			mSerialPort.setParams(BAUD_RATE, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

			// Listen for events
			mSerialPort.addEventListener(new SerialPortEventListener() {

				@Override
				public void serialEvent(SerialPortEvent event) {
					if (event.isRXCHAR()){
						if (event.getEventValue() == BYTES_MSG){
							handleReceive();
						}
					}
					else if (event.isERR()){
						mConnectionManager.onDisconnected();
					}
				}
			}, SerialPort.MASK_RXCHAR | SerialPort.MASK_ERR);

			return true;
		} catch (SerialPortException e){
			getLogger().logEvent(getName(), "Connection", "Error connecting: "+e.getMessage());
		}

		return false;
	}

	@Override
	public void disconnect() {
		if (mSerialPort != null){
			try {
				mSerialPort.closePort();
			} catch (SerialPortException e1) {
				e1.printStackTrace();
			}
		}
	}

	@Override
	public boolean probeConnection() {
		return false;
	}

	protected void stopInterfaceImpl() {
		// End serial eventing and close port
		mConnectionManager.stopConnection();
	}

	/**
	 * Called when a new message has been received from a enocean device
	 * @param packet a ESP3Packet containing the contents of the message
	 */
	public void messageReceived(ESP3Packet packet) {
		if (packet == null || packet.telegram == null) return;

		byte payload = packet.telegram.getPayload()[0];
		String sensorName = mDeviceMap.get(packet.telegram.getSenderID().toString()+":"+payload);
		if (sensorName != null && sensorName.contains("button")){
			double value = EnoceanSwitch.getState(payload);

			// Update processimage with this new event
			mData.clear();
			CompositeMeasurement measurement = new CompositeMeasurement(value, Quality.OK, Validity.GOOD, Source.PROCESS);
			mData.put(sensorName, measurement);
			notifyProcessImage();
			mConnectionManager.signal();
		}
		else{
			getLogger().logEvent(getName(), "Error", "Error receiving packet: "+packet.telegram.toString());
		}
	}

	@Override
	public boolean isConnected() {
		return mConnectionManager.isConnected();
	}

	@Override
	public void applyActuation(Actuator actuator) {
		// Not applicable for this interface
	}

	/**
	 * Receives a transmission by reading data from the associated InputStream and converting it to a ESP3Packet.
	 */
	public void handleReceive(){
		try {
			byte buffer[] = mSerialPort.readBytes(BYTES_MSG);

			ESP3Frame frame = new ESP3Frame(buffer, BYTES_MSG);
			frame.readPacket();

			// Use the packet
			messageReceived(frame.getPacket());
		}
		catch (SerialPortException ex) {
			mConnectionManager.onDisconnected();
		}
	}
}
